//index.js
//获取应用实例
var app = getApp()
import {
  getAddress
} from '../../api/address'
Page({
  data: {
    addressList: []
  },

  selectTap: function (e) {
    var id = e.currentTarget.dataset.id;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    let data = this.data.addressList.find(item => item.id == id);
    //直接调用上一个页面对象的setData()方法，把数据存到上一个页面中去
    console.log(data)
    prevPage.setData({
      curAddressData: data,
      newAdd: true
    });

    wx.navigateBack({
      id
    });

  },

  addAddess: function () {
    wx.navigateTo({
      url: "../address-add/address-add"
    })
  },

  editAddess: function (e) {
    console.log(e.currentTarget.dataset)
    let region = e.currentTarget.dataset.region.split(',')
    console.log(region)
    wx.navigateTo({
      url: "/pages/address-add/address-add?id=" +
        e.currentTarget.dataset.id + '&mobile=' +
        e.currentTarget.dataset.tel + '&name=' +
        e.currentTarget.dataset.name + '&region=' +
        JSON.stringify(region) + '&default=' +
        e.currentTarget.dataset.default
    })
  },

  onLoad: function () {
    var that = this;
    if (app.globalData.iphone == true) {
      that.setData({
        iphone: 'iphone'
      })
    }
    wx.hideShareMenu()
  },
  onShow: function () {
    if( !wx.getStorageSync('access_token') ) {
      wx.showModal({
        title: '请先登录',
        content: '',
        showCancel: false,
        success: (res) => {
          wx.navigateBack({
            delta: 1 //返回上一级页面
          })
        } 
      })
      return
    }
    this.initShippingAddress()
  },
  async initShippingAddress() {
    let addressData = await getAddress(app.globalData.userInfo.id, 1, 100, wx.getStorageSync('access_token'))
    let that = this
    console.log(addressData)
    if (addressData.code == 10000) {
      this.setData({
        addressList: addressData.data.records.map(item => {
          item.consigneeAddressPath = item.consigneeAddressPath.split(",").join(" ")
          return item
        }),
        loadingMoreHidden: true
      })
      if( that.data.addressList.length < 1 ){
        this.setData({
          loadingMoreHidden: false
        })
      }
    } else {
      that.setData({
        addressList: null,
        loadingMoreHidden: false
      })
    }
    // app.get('user/get_address_by_custid?CustId=' + app.globalData.uid, res => {
    //   console.log(res)
    //   if (res.code == 0) {
    //     that.setData({
    //        addressList:res.result,
    //        loadingMoreHidden: true
    //     });
    //   }else{
    //     that.setData({
    //       addressList: null,
    //       loadingMoreHidden: false
    //     })
    //   }
    // })
  }
})